import React, { Component } from 'react';

import { routerRedux, Route, Switch } from 'dva/router';

import Debounce from 'lodash-decorators/debounce';
import Bind from 'lodash-decorators/bind';
import { connect } from 'dva';
import {
  Button, Menu, Dropdown, Icon, Row, Col,
  Input, InputNumber,
  Steps, Card, Popover, Badge, Table, Tooltip, Divider,
  Checkbox, Modal, Radio,
  Select, message

} from 'antd';
import { getRoutes } from '../../utils/utils';
import classNames from 'classnames';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import DescriptionList from '../../components/DescriptionList';
import styles from './ApplyProfile.less';
import u620 from '../../assets/u620.png';
import u622 from '../../assets/u622.png';
import yes from '../../assets/yes.png';
import no from '../../assets/no.png';
import what1 from '../../assets/what1.png';
import querystring from 'querystring';
export let profileState6 = false;
const { Step } = Steps;
const TextArea = Input.TextArea;
const { Description } = DescriptionList;
const ButtonGroup = Button.Group;
const RadioGroup = Radio.Group;
const Option = Select.Option;
const confirm = Modal.confirm;

const getWindowWidth = () => (window.innerWidth || document.documentElement.clientWidth);

@connect(({ pendingTask, }) => ({
  pendingTask,
}))
export default class ApplyDetails6 extends Component {
  state = {
    id: '',
    taskId: '',
    operationkey: 'tab1',
    stepDirection: 'horizontal',
    modalVisible: false,
    profileState6: false,
    result: '',
    amount: '',
    note: '',
    history: {},
    historyNoteOne: '',
    historyNoteTwo: '',
    status: '',
    auditStatusList: [],
    custList: {},
    auditList: {},
    auditOpinionList: {},
    nextAuditModalVisible: false,
    auditStaff: null
  }

  componentDidMount() {
    const { dispatch, location } = this.props;
    const params = querystring.parse(location.search.slice(1));
    this.setState({
      id: params.custId,
      taskId: params.taskId,
      reviewState: params.reviewState,
    })
    if (params.custId != null) {
      dispatch({
        type: 'pendingTask/auditOpinion',
        payload: {
          id: params.custId,
        },
        callback: () => {
          const { pendingTask: { auditOpinionList, auditStatusList } } = this.props;
          // console.log("auditStatusList",auditStatusList)
          this.setState({
            auditStatusList: auditStatusList
          })
          auditOpinionList.audit &&
            this.setState({
              auditOpinionList: auditOpinionList.audit,
              history: auditOpinionList.history,
              amount: auditOpinionList.audit.amount,
              status: auditOpinionList.audit.status,
            })
          if (params.reviewState == 1) {//一审
            this.setState({
              historyNoteOne: "",
            })
          } else if (params.reviewState == 2) {//二审
            this.setState({
              historyNoteOne: auditOpinionList.history[0].note,
            })
          } else if (params.reviewState == 3) {//终审
            this.setState({
              historyNoteOne: auditOpinionList.history[0].note,
              historyNoteTwo: auditOpinionList.history[1].note,
            })
          }
        }
      });
    }
    dispatch({
      type: 'pendingTask/fetchApplyProfile',
      payload: {
        id: params.id,
      },
      callback: () => {
        const { pendingTask: { custMessgeList, custAuditList } } = this.props;

        this.setState({
          custList: custMessgeList,
          auditList: custAuditList
        })
      }
    });
    this.setStepDirection();
    window.addEventListener('resize', this.setStepDirection);
  }

  // componentWillUnmount() {
  //   window.removeEventListener('resize', this.setStepDirection);
  //   this.setStepDirection.cancel();
  // }

  onOperationTabChange = (key) => {
    this.setState({ operationkey: key });
  }

  @Bind()
  @Debounce(200)
  setStepDirection() {
    const { stepDirection } = this.state;
    const w = getWindowWidth();
    if (stepDirection !== 'vertical' && w <= 576) {
      this.setState({
        stepDirection: 'vertical',
      });
    } else if (stepDirection !== 'horizontal' && w > 576) {
      this.setState({
        stepDirection: 'horizontal',
      });
    }
  }

  handleSubmitModal = () => {
    this.setState({
      modalVisible: false,
    })
    // this.handleValueSubmit();
    this.state.result == 1 ? this.setState({ nextAuditModalVisible: true }):this.handleValueSubmit()
  }


  handleCancelSubmit = () => {
    this.setState({
      modalVisible: false,
    })
  }

  handleValueSubmit = () => {
    const { dispatch } = this.props;
    if (!this.state.auditStatusList[0]) {
      dispatch({
        type: 'pendingTask/commitCustomer',
        payload: {
          taskId: this.state.taskId,
        },
      });
    }
    if (!this.state.auditStatusList[1]) {
      dispatch({
        type: 'pendingTask/commitBusiness',
        payload: {
          taskId: this.state.taskId,
        },
      });
    }
    if (!this.state.auditStatusList[2]) {
      dispatch({
        type: 'pendingTask/commitCredit',
        payload: {
          taskId: this.state.taskId,
        },
      });
    }
    if (!this.state.auditStatusList[3]) {
      dispatch({
        type: 'pendingTask/commitAbility',
        payload: {
          taskId: this.state.taskId,
        },
      });
    }
    if (!this.state.auditStatusList[4]) {
      dispatch({
        type: 'pendingTask/commitGuarantee',
        payload: {
          taskId: this.state.taskId,
        },
      });
    }
    dispatch({
      type: 'pendingTask/saveAudit',
      payload: {
        id: this.state.auditList.id,
        amount: this.state.amount,
        result: this.state.result,
        note: this.state.note,
        operator: this.state.auditStaff
      },
      callback: () => {
        const { pendingTask: { result } } = this.props;
        if (result && result.code == '200') {
          this.props.dispatch(routerRedux.push('/review/completed-task'));
        }
      }
    });
  }

  handleClickSubmit = () => {
    const { dispatch } = this.props;
    let allStatus = this.state.status;
    let allStatusArray = allStatus.split("")
    if(this.state.reviewState != 3){
      dispatch({
        type:'pendingTask/getTaskOperator',
        payload:{ taskId: this.state.taskId}
      })
    }
    if (this.state.result == "") {
      message.warning("请选择审批结果")
    } else {
      if (this.state.reviewState == 2 || this.state.reviewState == 1) {
              
        if (allStatusArray[0] == '1' && allStatusArray[1] == '1' &&
          allStatusArray[2] == '1' && allStatusArray[3] == '1' &&
          allStatusArray[4] == '1') {

          this.state.result == 1 ? this.setState({ nextAuditModalVisible: true }):this.handleValueSubmit()
        } else {
          // this.showConfirm()
         
          this.setState({
            modalVisible: true,
          })
        }
      } else {
         this.handleValueSubmit()
      }
    }
    
  }

  handleIdentityValue = (e) => {
    this.setState({
      result: e.target.value
    })
  }
  handleAmount = (value) => {
    this.setState({
      amount: value
    })
  }
  handleNote = (e) => {
    this.setState({
      note: e.target.value
    })
  }

  handleAuditSubmitModal = () => {
    if (this.state.auditStaff) {
      this.handleValueSubmit();
      this.setState({
        nextAuditModalVisible: false
      })
    } else {
      message.warning("请选择下一级审核人员")
    }
  }

  handleAuditCancelSubmit = () => {
    this.setState({
      nextAuditModalVisible: false
    })
  }

  handleNextAuditChange = (value) => {
    // console.log("22222222222222222222", value)
    this.setState({auditStaff: value})
  }

  renderOption = (data) => {
    const options = [];
    data.map((item) => {
        options.push(<Option value={item.userName} key={item.id}>{item.name}</Option>)
    })
    return options;
  }

  render() {
    const { stepDirection } = this.state;
    const { pendingTask: { auditOpinionList, saveAuditLoading, taskOperatorList } } = this.props;
    const img = (<img alt="" src={u620} />);
    return (
      <Row>
        <Row>
          {/* {JSON.stringify(taskOperatorList)} */}
          <Col span={21}>
            <Card title="调查意见"
              bordered={false}>
              <span>
                我行贷前调查人员已按信贷管理的有关规定，
                履行了贷前尽职调查的责任与义务，
                并对所提供贷款资料的真实性、完整性、准确性负责，无其他应报未报事项。
                申请人提交与填写申请资料属实，资信正常，
                具备按时足额还款能力，抵(质)押物与保证担保足值合法有效。
              </span>
              <span>
                我行同意申请人
                <Input
                  style={{ width: 100, marginLeft: 6, marginRight: 6, marginTop: 10 }}
                  value={this.state.custList.custName}
                />
                办理
                <InputNumber style={{ width: 100, marginLeft: 6, marginRight: 6 }} value={this.state.custList.loanAmount} />
                元汽车专项分期付款，
                申请期限
                <InputNumber style={{ width: 100, marginLeft: 6, marginRight: 6 }} value={this.state.custList.duration} />月，
                手续费率
                <InputNumber style={{ width: 100, marginLeft: 6, marginRight: 6 }} value={this.state.custList.feeRate} />
                %。
              </span>
              <span>
                <Row style={{ marginTop: 30 }}>
                  同意其分期付款卡临时调升至人民币
                  <InputNumber
                    style={{ width: 100, marginLeft: 6, marginRight: 6, marginTop: 5 }}
                    value={this.state.amount}
                    onChange={this.handleAmount}
                  />
                  元整。
                </Row>
              </span>
              {
                this.state.historyNoteOne == "" ? null :
                  <Row style={{ marginTop: 30 }}>
                    一审意见: {this.state.historyNoteOne}
                  </Row>
              }
              {
                this.state.historyNoteTwo == "" ? null :
                  <Row style={{ marginTop: 30 }}>
                    二审意见: {this.state.historyNoteTwo}
                  </Row>
              }
              {
                <Row style={{ marginTop: 30 }}>
                  <DescriptionList className={styles.headerList} size="small" col="1">
                    <Description term="审批结果">
                      {
                        this.state.reviewState == 3 ?
                          <span>
                            <RadioGroup value={this.state.result} onChange={this.handleIdentityValue}>
                              <Radio value={"1"}>通过</Radio>
                              <Radio value={"3"}>拒绝</Radio>
                            </RadioGroup>
                            {this.state.result == "1" ? <img src={yes} /> : null}
                            {this.state.result == "3" ? <img src={no} /> : null}
                          </span>
                          :
                          <span>
                            <RadioGroup value={this.state.result} onChange={this.handleIdentityValue}>
                              <Radio value={"1"}>通过</Radio>
                              <Radio value={"2"}>驳回</Radio>
                              <Radio value={"3"}>拒绝</Radio>
                            </RadioGroup>
                            {this.state.result == "1" ? <img src={yes} /> : null}
                            {this.state.result == "2" || this.state.result == "3" ? <img src={no} /> : null}
                          </span>
                      }
                    </Description>
                  </DescriptionList>
                </Row>
              }

              <span>
                <TextArea
                  rows={4}
                  placeholder="其他意见"
                  style={{ marginBottom: 30, marginTop: 30 }}
                  value={this.state.note}
                  onChange={this.handleNote}
                />
              </span>
              <span style={{ textAlign: 'left' }}>
                <Button type="primary" onClick={this.handleClickSubmit} loading={saveAuditLoading}>提交</Button>
              </span>

            </Card>
          </Col>
        </Row>
        <Modal
          onOk={this.handleSubmitModal}
          onCancel={this.handleCancelSubmit}
          visible={this.state.modalVisible}>
          <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
            <Col span={4} style={{ paddingLeft: 20, marginLeft: 14, marginTop: 14, paddingTop: 10 }}>
              <img src={what1} style={{ width: 44, height: 44 }} />
            </Col>
            <Col span={20} style={{ marginTop: -35, float: 'right', marginLeft: -10 }}>

              <p style={{ color: '#000000', fontSize: '18px' }}>
                审批未完成，确定要提交吗?
              <br />
                <span style={{ fontSize: '14px' }}>
                  若提交，前面未完成的内容均为空,可能造成审核不能通过。
                </span>
              </p>
            </Col>
          </Row>
        </Modal>
        <Modal
          title="下级审核人员"
          onOk={this.handleAuditSubmitModal}
          onCancel={this.handleAuditCancelSubmit}
          visible={this.state.nextAuditModalVisible}>
          <Select
            style={{ width: '80%', margin: '0' }}
            placeholder="请选择审核人员"
            onChange={(value) => this.handleNextAuditChange(value)}
          >
            {taskOperatorList&&this.renderOption(taskOperatorList)}
            {/* <Option value="1">张小三三</Option> */}
          </Select>
        </Modal>
      </Row>
    );
  }
}
